package com.wuneng.ircontrol.module.act;

import android.Manifest;
import android.app.Dialog;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.bluetooth.BluetoothGatt;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.wuneng.ircontrol.common.util.CariGson;
import com.wuneng.ircontrol.common.util.Constants;
import com.wuneng.ircontrol.myUtil.common.LogUtil;
import com.wuneng.ircontrol.myUtil.common.Util;
import com.wuneng.ircontrol.myUtil.widget.ProgressDialogHelper;
import com.chaychan.library.BottomBarItem;
import com.chaychan.library.BottomBarLayout;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;

import com.wuneng.ircontrol.R;
import com.wuneng.ircontrol.common.util.BaseFragment;
import com.wuneng.ircontrol.common.util.MyBaseAct;
import com.wuneng.ircontrol.module.fragment.FragmentA;
import com.wuneng.ircontrol.module.fragment.FragmentB;
import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleGattCallback;
import com.clj.fastble.callback.BleNotifyCallback;
import com.clj.fastble.callback.BleWriteCallback;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.exception.BleException;

public class MainActivity extends MyBaseAct {


    @BindView(R.id.bbiOverAll)
    BottomBarItem bbiOverAll;
    @BindView(R.id.bbl)
    BottomBarLayout bbl;
    @BindView(R.id.main_container)
    FrameLayout mainContainer;

    private List<BaseFragment> mfragmentList = new ArrayList<>();
    private Dialog dialog;
    private FragmentA fragmentA;
    private FragmentB fragmentB;
    private BaseFragment mCurrentFragment;
    private FragmentManager mFragmentManager;
    private BleDevice myDevice;
    private long exitTime = 0;
    private static final long TIMEOUT_MILLS = 5 * 1000L;
    private Timer timer = new Timer();
    public byte[] ReadApertureAndFault = {(byte) 0x01, (byte) 0x03, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x03, (byte) 0x05, (byte) 0xCB};//读取开度
    public byte[] ReadTempAndHumi = {(byte) 0x01, (byte) 0x03, (byte) 0x00, (byte) 0x0B, (byte) 0x00, (byte) 0x02, (byte) 0xB5, (byte) 0xC9};//读取温湿度
    private boolean tag = true;

    public byte[] A = {(byte) 0x01, (byte) 0x03, (byte) 0x06, (byte) 0x00, (byte) 0x28, (byte) 0x00, (byte) 0x18, (byte) 0x00, (byte) 0x53, (byte) 0xA1, (byte) 0x4B};//读取开度

    @Override
    protected void initMyView() {
        dialog = ProgressDialogHelper.createLoadingDialog(this, "设备连接中");
    }

    @Override
    protected void initMyData() {
        fragmentA = new FragmentA();
        fragmentB = new FragmentB();
        mfragmentList.add(fragmentA);
        mfragmentList.add(fragmentB);
        mCurrentFragment = fragmentA;
        mFragmentManager = getFragmentManager();
        mFragmentManager.beginTransaction().add(R.id.main_container, fragmentA).commitAllowingStateLoss();
        checkPermission();
        timer.schedule(timeoutTask, TIMEOUT_MILLS, TIMEOUT_MILLS);


    }

    private TimerTask timeoutTask = new TimerTask() {
        @Override
        public void run() {
            if (tag) {
                sendOrder(ReadApertureAndFault);
            } else {
                sendOrder(ReadTempAndHumi);
            }
            tag = !tag;
        }
    };


    @Override
    protected void bindListener() {
        bbl.setOnItemSelectedListener(new BottomBarLayout.OnItemSelectedListener() {
            @Override
            public void onItemSelected(BottomBarItem bottomBarItem, int previousPosition, int currentPosition) {
                switchContent(mCurrentFragment, mfragmentList.get(currentPosition));
            }
        });
    }

    private void switchContent(BaseFragment from, BaseFragment to) {
        if (mCurrentFragment != to) {
            mCurrentFragment = to;
            FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
            if (!to.isAdded()) {    // 先判断是否被add过
                fragmentTransaction.hide(from).add(R.id.main_container, to).commitAllowingStateLoss(); // 隐藏当前的fragment，add下一个到Activity中
            } else {
                fragmentTransaction.hide(from).show(to).commitAllowingStateLoss(); // 隐藏当前的fragment，显示下一个
            }
        }
    }

    @Override
    protected int getMyContentViewLayoutID() {
        return R.layout.act_main;
    }


    private void checkPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, 1);
            } else {
            }
        } else {

        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == 1) {
//            BleDevice device = CariGson.getInstance().fromJson(data.getStringExtra("data"), new TypeToken<BleDevice>() {
//            }.getType());
            connectDevice(Constants.myDevice);
        }
    }


    private void connectDevice(BleDevice bleDevice) {
        BleManager.getInstance().connect(bleDevice, new BleGattCallback() {
            @Override
            public void onStartConnect() {
                dialog.show();
            }

            @Override
            public void onConnectFail(BleDevice bleDevice, BleException exception) {
                dialog.dismiss();
            }

            @Override
            public void onConnectSuccess(BleDevice bleDevice, BluetoothGatt gatt, int status) {
                dialog.dismiss();
                fragmentA.clearData();
                myDevice = bleDevice;
                openNotify();
            }

            @Override
            public void onDisConnected(boolean isActiveDisConnected, BleDevice device, BluetoothGatt gatt, int status) {
                Toast.makeText(THIS, "连接中断", Toast.LENGTH_LONG).show();
                fragmentA.setDeviceName("连接中断...");
                fragmentA.clearData();
            }
        });
    }


    private void openNotify() {
        BleManager.getInstance().notify(myDevice, "000a002-0000-1000-8000-00805f9b34fb", "0000c306-0000-1000-8000-00805f9b34fb", new BleNotifyCallback() {
            @Override
            public void onNotifySuccess() {
                fragmentA.setDeviceName(myDevice.getName());
            }

            @Override
            public void onNotifyFailure(BleException exception) {
                showToast("蓝牙设备监听失败,请重新连接");
            }

            @Override
            public void onCharacteristicChanged(byte[] data) {
                Log.e("aaa",Util.printData(data));
                try {
                    if (data[1] == (byte) 0x06) {
                        LogUtil.write("收到写入响应" + Util.printData(data));
                        switch ((data[2] & 0xFF) * 256 + data[3] & 0xFF) {
                            case 1:
                                if (((data[4] & 0xFF) * 256 + data[5] & 0xFF) == 100) {
                                    showToast("阀门开启成功");
                                } else {
                                    showToast("阀门关闭成功");
                                }
                                break;
                        }
                    } else {
                        fragmentA.refresh(data);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });
    }


    public void read() {
        if (tag) {
            sendOrder(ReadApertureAndFault);
        } else {
            sendOrder(ReadTempAndHumi);
        }
        tag = !tag;

    }


    public void sendOrder(byte[] order) {
        if (myDevice != null)
            BleManager.getInstance().write(myDevice,"0000a002-0000-1000-8000-00805f9b34fb", "0000c303-0000-1000-8000-00805f9b34fb", order, new BleWriteCallback() {
                @Override
                public void onWriteSuccess(int current, int total, byte[] justWrite) {
                    Log.e("aaa","数据写入成功");
                }

                @Override
                public void onWriteFailure(BleException exception) {
                    Log.e("aaa","数据写入失败"+CariGson.getInstance().toJson(exception));
                    LogUtil.write("数据写入失败" + exception.getDescription());
                }
            });

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        Constants.Login_Tag = false;
        if (myDevice != null)
            BleManager.getInstance().stopNotify(myDevice, "000a002-0000-1000-8000-00805f9b34fb", "0000c306-0000-1000-8000-00805f9b34fb");

    }

    @Override
    public void onBackPressed() {
        if (System.currentTimeMillis() - exitTime < 2000) {
            finish();
        } else {
            Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_LONG).show();
            exitTime = System.currentTimeMillis();
        }
    }
}
